package cn.cstor.mailtest.service.impl;

import cn.cstor.mailtest.constant.Constants;
import cn.cstor.mailtest.domain.User;
import cn.cstor.mailtest.mapper.UserMapper;
import cn.cstor.mailtest.redis.RedisCache;
import cn.cstor.mailtest.service.UserService;
import cn.cstor.mailtest.util.AjaxResult;
import cn.cstor.mailtest.vo.CodeUpdatePwdVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户信息 实现类
 *
 * @author zzw
 * @date 2022-05-03
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisCache redisCache;

    /**
     * 邮箱验证码重置密码
     *
     * @param codeUpdatePwdVo
     * @return
     */
    @Override
    public AjaxResult codeUpdatePwd(CodeUpdatePwdVo codeUpdatePwdVo) {
        String staffNumber = codeUpdatePwdVo.getStaffNumber();
        String code = codeUpdatePwdVo.getCode();
        String loginPassword = codeUpdatePwdVo.getLoginPassword();
        // 非空校验
        if (null == staffNumber || "".equals(staffNumber)) return AjaxResult.error("账号不能为空！");
        if (null == code || "".equals(code)) return AjaxResult.error("验证码不能为空！");
        if (null == loginPassword || "".equals(loginPassword)) return AjaxResult.error("密码不能为空！");

        // 账号存在校验
        User user = userMapper.selectUserByStaffNumber(staffNumber);
        if (null == user) {return AjaxResult.error("账号不存在！");}

        // 验证码过期校验
        // 获取缓存中该账号的验证码
        String cacheCode = redisCache.getCacheObject(Constants.MAIL_CODE_KEY + staffNumber);
        if (cacheCode == null) {
            return AjaxResult.error("验证码已过期，请重新获取！");
        }

        // 验证码正确性校验
        if (!cacheCode.equals(code)) {
            return AjaxResult.error("验证码错误！");
        }

        // 修改密码
        int result = userMapper.updatePwdByStaffNumber(staffNumber, codeUpdatePwdVo.getLoginPassword());
        if (result > 0) {
            // 将验证码过期
            redisCache.expire(Constants.MAIL_CODE_KEY + staffNumber, 0);
            return AjaxResult.success("密码重置成功！请牢记您的密码！");
        }

        return AjaxResult.error("未知错误，密码修改失败，请重试！");
    }
}
